import tkinter as tk
import socket
import cv2
import numpy as np
import threading

# 服务器IP和端口
SERVER_IP = "192.168.10.1"
SERVER_PORT = 8888

# 创建主窗口
root = tk.Tk()
root.title("火灾报警监控系统")

# 创建标题标签
title_label = tk.Label(root, text="火灾报警监控系统", font=("Helvetica", 20, "bold"))
title_label.pack(side=tk.TOP, fill=tk.X, pady=10)

# 创建显示栏框架
display_frame = tk.Frame(root, width=400, height=600)
display_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)
display_frame.pack_propagate(False)  # 禁止框架自动调整大小

# 视频显示区域（使用Label来显示图像）
video_label = tk.Label(display_frame)
video_label.pack(side=tk.TOP, fill=tk.BOTH, expand=True, padx=5, pady=5)

# 警告信息显示区域
warning_label = tk.Label(display_frame, text="", height=3, width=50, anchor=tk.W, justify=tk.LEFT, font=("Helvetica", 12, "bold"), bg="yellow")
warning_label.pack(side=tk.BOTTOM, fill=tk.X, padx=5, pady=5)

# 创建操作控制栏框架
control_frame = tk.Frame(root, width=200, height=600)
control_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=False, padx=5, pady=5)
control_frame.pack_propagate(False)  # 禁止框架自动调整大小

# 蜂鸣器开关按钮
buzzer_button = tk.Button(control_frame, text="蜂鸣器开关", command=lambda: send_command("1"), font=("Helvetica", 16, "bold"), height=2, width=10)
buzzer_button.pack(side=tk.TOP, padx=5, pady=5)

# 检查火焰按钮
check_flame_button = tk.Button(control_frame, text="检查火焰", command=lambda: send_command("check_flame"), font=("Helvetica", 16, "bold"), height=2, width=10)
check_flame_button.pack(side=tk.TOP, padx=5, pady=5)

# 退出系统按钮
exit_button = tk.Button(control_frame, text="退出系统", command=root.quit, font=("Helvetica", 16, "bold"), height=2, width=10)
exit_button.pack(side=tk.TOP, padx=5, pady=5)

# 创建套接字并连接服务器
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((SERVER_IP, SERVER_PORT))

# 发送指令到服务器的函数
def send_command(command):
    def send_and_receive():
        try:
            client_socket.send(command.encode('utf-8'))
            response = client_socket.recv(1024).decode('utf-8')
            warning_label.config(text=response)
        except socket.error as e:
            warning_label.config(text=f"与服务器通信出错: {str(e)}")
    threading.Thread(target=send_and_receive).start()

# 用于更新视频显示的函数，在单独线程中运行
def update_video():
    video_url = "http://192.168.10.1:8080/?action=stream"
    cap = cv2.VideoCapture(video_url)
    if not cap.isOpened():
        print("无法打开视频流")
        return

    while True:
        ret, frame = cap.read()
        if not ret:
            print("无法接收视频帧，可能是视频流结束或连接出现问题")
            break
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        photo = tk.PhotoImage(data=cv2.imencode('.png', frame)[1].tobytes())
        video_label.config(image=photo)
        video_label.image = photo
        root.update_idletasks()  # 确保UI更新
    cap.release()

# 启动视频显示线程
video_thread = threading.Thread(target=update_video)
video_thread.start()

# 主事件循环
root.mainloop()

# 关闭套接字连接
client_socket.close()
